package com.mg.g2048.Touch;

import android.content.Context;
import android.graphics.PointF;
import android.util.Log;
import android.view.MotionEvent;

import com.mg.g2048.MainActivity;
import com.mg.g2048.MessageCode;
import com.mg.g2048.R;
import com.mg.g2048.TouchCode;
import com.mg.g2048.Data.DataCenter;

public class TouchDetector {

	// 五指初始距离
	private double minTouch = 300;
	// 五指初始距离
	private double maxTouch = 300;
	// 五指结束距离
	private double endDisFiveFinger = 0;
	// 五指变化距离
	private double disZoomFiveFinger = 0;
	// 触摸点信息
	private PointF points = new PointF();
	// 五指初始重心
	private PointF startBarycenterFiveFinger = new PointF(0, 0);
	// 五指结束重心
	private PointF endBarycenterFiveFinger = new PointF(0, 0);

	public TouchDetector(Context context){
		minTouch = DataCenter.screenWidth / 3;
		maxTouch = DataCenter.screenWidth / 3;
	}
	
	public void getTouchEvent(MotionEvent event) {
		freshEvents(event);
	}
	
	/**
	 * 由触屏信息更新事件数据
	 * 
	 * @param event 触屏信息
	 * 
	 */
	private void freshEvents(MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		// 无效触屏事件
		case MotionEvent.ACTION_CANCEL:
			break;

		// 按下时，设置双指缩放起点
		case MotionEvent.ACTION_DOWN:{
				int pointerCount = event.getPointerCount();
				// 一个手指的动作
				if (pointerCount == 1) {
					startBarycenterFiveFinger = new PointF(event.getX(0), event.getY(0));
				}
			}
			break;

		// 放开时，设置双指缩放终点
		case MotionEvent.ACTION_UP:{
				int pointerCount = event.getPointerCount();
				// 一个手指的动作
				if (pointerCount == 1) {
					endBarycenterFiveFinger = new PointF(event.getX(0), event.getY(0));
					float x = endBarycenterFiveFinger.x - startBarycenterFiveFinger.x;
					float y = endBarycenterFiveFinger.y - startBarycenterFiveFinger.y;
					if(x < minTouch && x > -minTouch)
						if(y < minTouch && y > -minTouch){
							MainActivity.sendMainHandlerMessage(MessageCode.INTERFACE_TOUCH_ACTION, TouchCode.TOO_MIN);
							return;
						}
					if(x > minTouch || x < -minTouch)
						if(y > maxTouch || y < -maxTouch){
							MainActivity.sendMainHandlerMessage(MessageCode.INTERFACE_TOUCH_ACTION, TouchCode.TOO_LONG);
							return;
						}
					if(x > minTouch){
						if(y < maxTouch && y > -maxTouch){
							MainActivity.sendMainHandlerMessage(MessageCode.INTERFACE_TOUCH_ACTION, TouchCode.RIGHT);
						}
					}
					else if(x < -minTouch){
						if(y < maxTouch && y > -maxTouch){
							MainActivity.sendMainHandlerMessage(MessageCode.INTERFACE_TOUCH_ACTION, TouchCode.LEFT);
						}
					}
					else if(x < maxTouch && x > -maxTouch){
						if(y > minTouch){
							MainActivity.sendMainHandlerMessage(MessageCode.INTERFACE_TOUCH_ACTION, TouchCode.DOWN);
						}
						else if(y < -minTouch){
							MainActivity.sendMainHandlerMessage(MessageCode.INTERFACE_TOUCH_ACTION, TouchCode.UP);
						}
					}
				}
			}
			break;
		default:
			break;
		}
	}
}
